package com.woniuxy.project115.kaer.platform.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.project115.kaer.commons.util.Result;
import com.woniuxy.project115.kaer.platform.Param.ApproveParam;
import com.woniuxy.project115.kaer.platform.dto.AccountDto;
import com.woniuxy.project115.kaer.platform.dto.LoginDto;
import com.woniuxy.project115.kaer.platform.entity.*;
import com.woniuxy.project115.kaer.platform.mapper.*;
import com.woniuxy.project115.kaer.platform.service.AccountService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.woniuxy.project115.kaer.platform.util.RedisKey;
import com.woniuxy.project115.kaer.tenant.dto.SettledApplicationDto;
import com.woniuxy.project115.kaer.tenant.form.ApproveApplicationForm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.woniuxy.project115.kaer.tenant.feign.TenantFeignClient;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author fyy
 * @since 2025年02月23日
 */
@Service
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements AccountService {
    @Resource
    private AccountMapper accountMapper;
    @Resource
    private AccountRoleMapper accountRoleMapper;
    @Resource
    private RoleMapper roleMapper;
    @Resource
    private LoginLogMapper loginLogMapper;
    @Resource
    private TenantFeignClient tenantFeignClient;
    @Resource
    private PermissionMapper permissionMapper;
    @Resource
    private RedisTemplate<String,Object> redisObjectTemplate;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void addAdmin(String userName, String passWord) throws Exception {
        //判断是否存在管理员
        final QueryWrapper<Account> accountQueryWrapper = new QueryWrapper<>();
        accountQueryWrapper.eq("user_name",userName);
        Account account = accountMapper.selectOne(accountQueryWrapper);
        if(account!= null){
            throw new Exception("管理员已存在");
        }
        //添加管理员
        Account admin = new Account();
        admin.setUserName(userName);
        admin.setPassWord(passWord);
        admin.setState("正常");
        admin.setCreateTime(LocalDateTime.now());
        accountMapper.insert(admin);
        //添加管理员角色
        final AccountRole accountRole = new AccountRole();
        accountRole.setAccountId(admin.getId());
        accountRole.setRoleId(2);
        accountRole.setCreatedTime(LocalDateTime.now());
        accountRoleMapper.insert(accountRole);
    }


    @Override
    public LoginDto login(String username, String password, HttpServletRequest req) throws Exception {
        //查询用户
        final QueryWrapper<Account> accountQueryWrapper = new QueryWrapper<>();
        accountQueryWrapper.eq("user_name",username);
        Account account = accountMapper.selectOne(accountQueryWrapper);
        if(account == null){
            throw new Exception("管理员不存在");
        }
        //验证密码
        if(!account.getPassWord().equals(password)){
            throw new Exception("密码错误");
        }
        //查询角色
        final QueryWrapper<AccountRole> accountRoleQueryWrapper = new QueryWrapper<>();
        accountRoleQueryWrapper.eq("account_id",account.getId());
        final AccountRole accountRole = accountRoleMapper.selectOne(accountRoleQueryWrapper);

        final QueryWrapper<Role> roleQueryWrapper = new QueryWrapper<>();
        roleQueryWrapper.eq("id",accountRole.getRoleId());
        final Role role = roleMapper.selectOne(roleQueryWrapper);
        if(role == null){
            throw new Exception("角色不存在");
        }

        //查询角色权限并存入到redis中
        List<String> permissions = permissionMapper.selectPermissionsByRoleId(role.getId());
        redisObjectTemplate.opsForValue().set(RedisKey.USER_PERMISSION_LIST(account.getId()), permissions);

        //创建登录信息
        final LoginLog loginLog = new LoginLog();
        loginLog.setAccountId(account.getId());
        loginLog.setLoginTime(LocalDateTime.now());
        String remoteHost = req.getRemoteHost();//获取远程主机地址
        loginLog.setLoginIp(remoteHost);
        loginLogMapper.insert(loginLog);
        //返回登录信息
        final LoginDto loginDto = new LoginDto();
        loginDto.setUserId(account.getId());
        loginDto.setUserName(account.getUserName());
        loginDto.setRole(role.getRoleName());
        return loginDto;
    }

    @Override
    public void agreeApply(ApproveParam param) throws Exception {
        //同意申请
        tenantFeignClient.approveApplication(BeanUtil.toBean(param, ApproveApplicationForm.class));
    }


    @Override
    public List<SettledApplicationDto> queryApply() throws Exception {
        //查询待处理的申请
        final Result<SettledApplicationDto> pendingApplication = tenantFeignClient.getPendingApplication();
        //判断是否有待处理的申请
        if(pendingApplication.getData() == null){
            throw new Exception("暂无待处理的申请");
        }
        //返回待处理的申请
        return pendingApplication.getList();
    }

    @Override
    public List<AccountDto> getAllAdmin() {
        //查询所有管理员
        final List<Account> accounts = accountMapper.selectList(null);
        //查询每个管理员账号对应的角色
        final ArrayList<AccountDto> accountDtos = new ArrayList<>();
        for (Account account : accounts) {
            final QueryWrapper<AccountRole> accountRoleQueryWrapper = new QueryWrapper<>();
            accountRoleQueryWrapper.eq("account_id",account.getId());
            final AccountRole accountRole = accountRoleMapper.selectOne(accountRoleQueryWrapper);
            final QueryWrapper<Role> roleQueryWrapper = new QueryWrapper<>();
            roleQueryWrapper.eq("id",accountRole.getRoleId());
            final Role role = roleMapper.selectOne(roleQueryWrapper);
            final AccountDto accountDto = new AccountDto();
            accountDto.setId(account.getId());
            accountDto.setUserName(account.getUserName());
            accountDto.setAccountRole(role.getRoleName());
            accountDto.setCreatTime(accountRole.getCreatedTime().toString());
            accountDtos.add(accountDto);
        }
        return accountDtos;
    }
    @Override
    public void deleteAdmin(String id) throws Exception {
        //查看该id是否存在
        final QueryWrapper<Account> accountQueryWrapper = new QueryWrapper<>();
        accountQueryWrapper.eq("id",id);
        final Account account = accountMapper.selectOne(accountQueryWrapper);
        if(account == null){
            throw new Exception("管理员不存在");
        }
        //删除管理员
        final QueryWrapper<Account> Wrapper = new QueryWrapper<>();
        Wrapper.eq("id",id);
        accountMapper.delete(Wrapper);
        //删除管理员角色
        final QueryWrapper<AccountRole> accountRoleQueryWrapper = new QueryWrapper<>();
        accountRoleQueryWrapper.eq("account_id",id);
        accountRoleMapper.delete(accountRoleQueryWrapper);
    }
}
